package ru.amse.tsyganov.jumleditor.properties;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.widgets.TableItem;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.commands.CommandFactory;
import ru.amse.tsyganov.jumleditor.commands.ViewsManager;

public class PropertiesCellModifier implements ICellModifier {
	
	private final TableViewer propertiesTableViewer;
	
	private final ViewsManager viewsManager;
	
	private final CellEditor propertyNameEditor;
		
	public PropertiesCellModifier(TableViewer propertiesTableViewer,
			ViewsManager viewsManager) {
		
		this.propertiesTableViewer = propertiesTableViewer;
		this.viewsManager = viewsManager;
		propertyNameEditor = 
			new TextCellEditor(propertiesTableViewer.getTable());
	}

	public boolean canModify(Object element, String property) {
		Property p = (Property) element;
		
		propertiesTableViewer.setCellEditors(new CellEditor[] {
				propertyNameEditor,
				p.getCellEditor(propertiesTableViewer.getTable())
		});
		
		if (PropertiesTable.PROPERTY_VALUE.equals(property)) {
			return p.canModify();
		} else {
			return false;
		}
	}

	public Object getValue(Object element, String property) {
		
		int columnIndex = PropertiesTable.PROPERTY_NAME.equals(property) ?
				PropertiesTable.PROPERTY_NAME_COLUMN_INDEX :
					PropertiesTable.PROPERTY_VALUE_COLUMN_INDEX;
		
		Property p = (Property) element;

		switch (columnIndex) {
			case PropertiesTable.PROPERTY_NAME_COLUMN_INDEX :  
				return p.getPropertyName();
			case PropertiesTable.PROPERTY_VALUE_COLUMN_INDEX :
				return p.getPropertyValue();
			default :
				return null;
		}
	}

	public void modify(Object element, String property, Object value) {	
		int columnIndex = PropertiesTable.PROPERTY_NAME.equals(property) ?
				PropertiesTable.PROPERTY_NAME_COLUMN_INDEX :
					PropertiesTable.PROPERTY_VALUE_COLUMN_INDEX;
			
		TableItem item = (TableItem) element;
		Property p = (Property) item.getData();
		
		switch (columnIndex) {
			case PropertiesTable.PROPERTY_NAME_COLUMN_INDEX :
				throw new IllegalStateException();
			case PropertiesTable.PROPERTY_VALUE_COLUMN_INDEX :
				if (!p.getPropertyValue().equals(value)) {
					Command c = CommandFactory.createChangePropertyCommand(p, value); 
					viewsManager.executeCommand(c);
				}
				break;
			default:
				throw new IllegalStateException();
		}
	}
}
